package com.etc.util;

import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import com.baidu.aip.face.AipFace;
import com.baidu.aip.face.MatchRequest;

public class BaiduAiUtil {
	private String App_ID = "21292262";
	private String API_KEY = "6C3Kx7EEc9MvWG33nAqQAaLw";
	private String SECRET_KEY = "KBmLwvBo1N3DyswvrnEWrOhxfClTpreY";
	private String IMAGE_TYPE = "BASE64";
	private String groupId = "rwencxc";
	private AipFace client = new AipFace(App_ID, API_KEY, SECRET_KEY);
	private HashMap<String, String> options = new HashMap<>();
	public BaiduAiUtil() {
		options.put("quality_control", "NORMAL");//图片质量 NONE LOW NORMAL HIGH
		options.put("liveness_control", "NORMAL");//活体检测 NONE LOW NORMAL HIGH
		
	}
	
	//判断用户是否已经注册面部信息
	public boolean faceExist(String id) {
		//返回error_code:0(存在)  非0:不存在
		JSONObject res = client.getUser(id, groupId, options);
		Integer errorCode = res.getInt("error_code");
		return errorCode == 0 ? true : false; 
	}
	
	/**
	 * 人脸注册:将用户照片存入人脸库中 
	 */
	public boolean faceRegister(String userId,String image) {
		JSONObject res = client.addUser(image, IMAGE_TYPE, groupId, userId, options);
		System.out.println(res);
		Integer errorCode = res.getInt("error_code");
		return errorCode == 0 ? true : false;
	}
	
	/**
	 * 人脸更新:更新人脸库中的用户照片
	 */
	public boolean faceUpdate(String userId,String image) {
		JSONObject res = client.updateUser(image, IMAGE_TYPE, groupId, userId, options);
		Integer errorCode = res.getInt("error_code");
		return errorCode == 0 ? true : false;
	}
	
	/**
	 * 人脸检测:判断上传图片中是否具有面部头像
	 */
	public boolean faceCheck(String image) {
		JSONObject res = client.detect(image, IMAGE_TYPE, options);
		System.out.println(res);
		if(res.has("error_code") && res.getInt("error_code")==0) {
			JSONObject resultObject = res.getJSONObject("result");
			Integer faceNum = resultObject.getInt("face_num");//当前检测的人脸数量
			return faceNum == 1 ? true : false;
		}
		return false;
	}
	
	/**
	 * 人脸搜索:查找人脸库中最相似的人脸并返回数据
	 * 			处理:用户的匹配得分(score)大于80分,即可认为是同一个用户
	 */
	public String faceSearch(String image) {
		JSONObject res = client.search(image, IMAGE_TYPE, groupId, options);
		System.out.println(res);
		if(res.has("error_code") && res.getInt("error_code")==0) {
			JSONObject result = res.getJSONObject("result");
			JSONArray userlist = result.getJSONArray("user_list");
			if(userlist.length() > 0) {
				JSONObject user = userlist.getJSONObject(0);
				double score = user.getDouble("score");
				if(score > 80) {
					return user.getString("user_id");
				}
			}
		}
		return null;
	}
	
}
